package com.yunwushanhe.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yunwushanhe.constant.Constant;
import com.yunwushanhe.entity.LoginUser;
import com.yunwushanhe.entity.User;
import com.yunwushanhe.mapper.MenuMapper;
import com.yunwushanhe.mapper.UserMapper;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.List;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private UserMapper userMapper;
    @Resource
    private MenuMapper menuMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        LambdaQueryWrapper<User> qw = new LambdaQueryWrapper<>();
        qw.eq(User::getUserName,username);
        User user = userMapper.selectOne(qw);
        if(ObjectUtils.isEmpty(user)){
            throw new RuntimeException("用户不存在");// 这里应该会导致 AuthenticationManager 类抛出认证失败的相关异常，
            // 并不会交给全局异常处理器处理
        }
        // 如果是后台用户则需要查询权限信息
        if(user.getType().equals(Constant.IS_ADMIN)){
            List<String> permissionList = menuMapper.selectPermListByUserId(user.getId());
            return new LoginUser(user,permissionList);
        }
        return new LoginUser(user);
    }
}
